package ro.romanescu.utilities;

import java.io.FileInputStream;
import java.io.IOException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import java.util.Properties;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;


public class TestUtilities {
  private static final Logger log = LogManager.getLogger( TestUtilities.class );
  private Properties settings = new Properties();
  
  
  /**
   * Read the configuration file and load the testing environmnent.
   * @throws IOException If failure during configuration file loading
   */
  public void configureEnvironment() throws IOException {
    log.info( "Loading test environment settings from test.properties file." );
    settings.load( new FileInputStream( "test.properties" ) );
  }
  
  
  /**
   * Retrieve an database connection according to settings from the configuration file.
   * @param namespace from the configuration file. For example in eximius.useradmin.jdbc.driver,
   * namespace is "eximius.useradmin".
   * @return A valid database connection or null if error occurrs
   */
  public Connection getDatabaseConnection( String namespace ) {
    Connection ret = null;
    try {
      Class.forName( settings.getProperty( namespace + ".jdbc.driver" ) );
      ret = DriverManager.getConnection( settings.getProperty( namespace + ".jdbc.url" ), 
                                   settings.getProperty( namespace + ".jdbc.user" ), 
                                   settings.getProperty( namespace + ".jdbc.pass" ) );
    }
    catch( ClassNotFoundException ex ) {
      log.error( "Error finding database driver", ex );
    }
    catch( SQLException ex ) {
      log.error( "Error obtaining database connection", ex );
    }
    return ret;
  }
}
